package com.ls.jpushMessageClient;

/**
 * 极光推送工具类
 * 利用别名alias 推送默认一次最多可以推送1000个 可以找激光商务调整
 * 当然也可以利用别的推送，暂时只是用别名推送就足够啦.
 */

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.ApacheHttpClient;
import cn.jiguang.common.connection.HttpProxy;
import cn.jiguang.common.connection.NettyHttpClient;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;

import java.util.Arrays;

public class JPushUtils2 {
    protected static final Logger log = Logger.getLogger(JPushUtils2.class);

    private static final String appKey ="58715abe24840c10ffa5ac74";
    private static final String masterSecret = "135f237c173bfbd04db23e1c";


    public static final String TITLE = "Test from API example";
    public static final String ALERT = "Test from API Example - alert";
    public static final String MSG_CONTENT = "Test from API Example - msgContent";
    public static final String REGISTRATION_ID = "0900e8d85ef";
    public static final String TAG = "tag_api";


    public static boolean sendAndroidMessageWithAlias(String title,String msg,String...alias){
        System.out.println("msg:"+msg);
        JPushClient jpushClient = new JPushClient(masterSecret, appKey);
        boolean flag = false;
        try {
            log.info("Android推送inner start");
            PushResult result = jpushClient.sendAndroidMessageWithAlias(title, msg,alias);
            log.info("推送inner success end alias:"+Arrays.asList(alias));
            flag = true;
            if(log.isDebugEnabled())
                log.debug(String.format("sendAndroidMessageWithAlias result:%s",JSONObject.toJSONString(result)));
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ");
        } catch (APIRequestException e) {
            log.error("Should review the error, and fix the request", e);
            log.error("HTTP Status: " + e.getStatus());
            log.error("Error Code: " + e.getErrorCode());
            log.error("Error Message: " + e.getErrorMessage());
        }finally{
            return flag;
        }
    }


    public static boolean sendIosMessageWithAlias(String title,String msg,String...alias){
        JPushClient jpushClient = new JPushClient(masterSecret, appKey);
        boolean flag = false;
        try {
            log.info("IOS推送inner start");
            PushResult result = jpushClient.sendIosMessageWithAlias(title, msg,alias);
            log.info("推送inner success end alias:"+Arrays.asList(alias));
            flag = true;
            if(log.isDebugEnabled())
                log.debug(String.format("sendIosMessageWithAlias result:%s",JSONObject.toJSONString(result)));
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ");
        } catch (APIRequestException e) {
            log.error("Should review the error, and fix the request", e);
            log.error("HTTP Status: " + e.getStatus());
            log.error("Error Code: " + e.getErrorCode());
            log.error("Error Message: " + e.getErrorMessage());
        }finally{
            return flag;
        }
    }


    public static boolean sendAllPlatformMessageWithAlias(String title,String msg,String...alias){
        JPushClient jpushClient = new JPushClient(masterSecret, appKey);
        boolean flag = false;
        try {
            PushPayload build = PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.alias(alias))
                    .setMessage(Message.newBuilder().setTitle(title).setMsgContent(msg).build())
                    .build();
            log.info("AllPlatform推送inner start");
            PushResult result = jpushClient.sendPush(build);
            log.info("推送inner success end alias:"+Arrays.asList(alias));
            flag = true;
            if(log.isDebugEnabled())
                log.debug(String.format("sendAllPlatformMessageWithAlias result:%s",JSONObject.toJSONString(result)));
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ");
        } catch (APIRequestException e) {
            log.error("Should review the error, and fix the request", e);
            log.error("HTTP Status: " + e.getStatus());
            log.error("Error Code: " + e.getErrorCode());
            log.error("Error Message: " + e.getErrorMessage());
        }finally{
            return flag;
        }
    }


    public static boolean sendAllPlatformNotificationWithAlias(String msg,String...alias){
        JPushClient jpushClient = new JPushClient(masterSecret, appKey);
        boolean flag = false;
        try {
            PushPayload build = PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                    .setAudience(Audience.alias(alias))
                    .setNotification(Notification.alert(msg))
                    .build();
            log.info("sendAllPlatformNotificationWithAlias推送inner start");
            PushResult result = jpushClient.sendPush(build);
            log.info("推送inner success end alias:"+Arrays.asList(alias));
            flag = true;
            if(log.isDebugEnabled())
                log.debug(String.format("sendAllPlatformMessageWithAlias result:%s",JSONObject.toJSONString(result)));
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ");
        } catch (APIRequestException e) {
            log.error("Should review the error, and fix the request", e);
            log.error("HTTP Status: " + e.getStatus());
            log.error("Error Code: " + e.getErrorCode());
            log.error("Error Message: " + e.getErrorMessage());
        }finally{
            return flag;
        }
    }


    public static boolean sendAndroidPlatformNotificationWithAlias(String msg,String...alias){
        long l = System.currentTimeMillis();
        System.out.println(String.format("{'time':%d,'msg':'%s'}",l,msg));
        JPushClient jpushClient = new JPushClient(masterSecret, appKey);
        boolean flag = false;
        try {
            PushPayload build = PushPayload.newBuilder()
                    .setPlatform(Platform.android())
                    .setAudience(Audience.alias(alias))
                    .setNotification(Notification.alert(msg))
                    .build();
            log.info("sendAndroidPlatformNotificationWithAlias推送inner start");
            PushResult result = jpushClient.sendPush(build);
            System.out.println(System.currentTimeMillis()-l);
            log.info("推送inner success end alias:"+Arrays.asList(alias));
            flag = true;
            if(log.isDebugEnabled())
                log.debug(String.format("sendAndroidPlatformNotificationWithAlias result:%s",JSONObject.toJSONString(result)));
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ");
        } catch (APIRequestException e) {
            log.error("Should review the error, and fix the request", e);
            log.error("HTTP Status: " + e.getStatus());
            log.error("Error Code: " + e.getErrorCode());
            log.error("Error Message: " + e.getErrorMessage());
        }finally{
            return flag;
        }
    }

    public static JPushClient static_jpushClient=null;
    public static JPushClient getJPushClient(boolean isNetty,boolean isAapche){
        JPushClient jpushClient = new JPushClient(masterSecret, appKey);
        //经测试高并发需求，可以使用ApacheHttpClient   NettyHttpClient会卡住，目前没有查找原因
        if(isNetty){
            if(static_jpushClient!=null) return static_jpushClient;
            String authCode = ServiceHelper.getBasicAuthorization(appKey, masterSecret);
            NettyHttpClient nettyHttpClient = new NettyHttpClient(authCode,(HttpProxy) null,ClientConfig.getInstance());
            jpushClient.getPushClient().setHttpClient(nettyHttpClient);
            static_jpushClient=jpushClient;
            return static_jpushClient;
        }else if(isAapche){
            if(static_jpushClient!=null) return static_jpushClient;
            String authCode = ServiceHelper.getBasicAuthorization(appKey, masterSecret);
            ApacheHttpClient apacheHttpClient = new ApacheHttpClient(authCode,(HttpProxy) null,ClientConfig.getInstance());
            jpushClient.getPushClient().setHttpClient(apacheHttpClient);
            static_jpushClient=jpushClient;
            return static_jpushClient;
        }
        return jpushClient;
    }
    public static boolean sendAndroidPlatformNotificationWithAlias(JPushClient jpushClient,String msg,String...alias){
        long l = System.currentTimeMillis();
        System.out.println(String.format("{'time':%d,'msg':'%s','hashCode':%d}",l,msg,jpushClient.hashCode()));
        boolean flag = false;
        try {
            PushPayload build = PushPayload.newBuilder()
                    .setPlatform(Platform.android())
                    .setAudience(Audience.alias(alias))
                    .setNotification(Notification.alert(msg))
                    .build();
            log.info("sendAndroidPlatformNotificationWithAlias推送inner start");
            PushResult result = jpushClient.sendPush(build);
            System.out.println(System.currentTimeMillis()-l);
            log.info("推送inner success end alias:"+Arrays.asList(alias));
            flag = true;
            if(log.isDebugEnabled())
                log.debug(String.format("sendAndroidPlatformNotificationWithAlias result:%s",JSONObject.toJSONString(result)));
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ");
        } catch (APIRequestException e) {
            log.error("Should review the error, and fix the request", e);
            log.error("HTTP Status: " + e.getStatus());
            log.error("Error Code: " + e.getErrorCode());
            log.error("Error Message: " + e.getErrorMessage());
        }finally{
            return flag;
        }
    }

    public static boolean sendIosPlatformNotificationWithAlias(String msg,String...alias){
        long l = System.currentTimeMillis();
        System.out.println(l);
        JPushClient jpushClient = new JPushClient(masterSecret, appKey);
        boolean flag = false;
        try {
            PushPayload build = PushPayload.newBuilder()
                    .setPlatform(Platform.ios())
                    .setAudience(Audience.alias(alias))
                    .setNotification(Notification.alert(msg))
                    .build();
            log.info("sendIosPlatformNotificationWithAlias推送inner start");
            PushResult result = jpushClient.sendPush(build);
            System.out.println(System.currentTimeMillis()-l);
            log.info("推送inner success end alias:"+Arrays.asList(alias));
            flag = true;
            if(log.isDebugEnabled())
                log.debug(String.format("sendIosPlatformNotificationWithAlias result:%s",JSONObject.toJSONString(result)));
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ");
        } catch (APIRequestException e) {
            log.error("Should review the error, and fix the request", e);
            log.error("HTTP Status: " + e.getStatus());
            log.error("Error Code: " + e.getErrorCode());
            log.error("Error Message: " + e.getErrorMessage());
        }finally{
            return flag;
        }
    }


}


